package br.gerenciadorAudio.BLL;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.gerenciadorAudio.ListProfileActivity;
import br.gerenciadorAudio.Schedule;
import br.gerenciadorAudio.DB.Repositorio;
import br.gerenciadorAudio.DB.SqLiteCursor;
import br.gerenciadorAudio.Model.Profile;
import br.gerenciadorAudio.Model.ProfileSchedule;
import br.gerenciadorAudio.Repository.RepositoryProfileScheduleScript;
import br.gerenciadorAudio.Repository.RepositoryProfileScript;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.util.Log;
import android.widget.Toast;

public class RegraNegocio {
	
	private static Repositorio r;
	
	public RegraNegocio(Context context)
	{
		r = new Repositorio(context);
	}
	
	public void CriarBancoDados(Context context)
	{
		String[] script = new String[]{RepositoryProfileScript.CreateTableProfile(),
									RepositoryProfileScheduleScript.CreateTable()};
		
		 r = new Repositorio(context,script, "");
	}
	
	public long Insert(Profile profile)
	{
		return r.Insert(RepositoryProfileScript.InserirTbPerfil(profile),Profile.Colunas.Tabela);
	}
	
	public long Insert(ProfileSchedule profileSchedule)
	{
		return r.Insert(RepositoryProfileScheduleScript.Insert(profileSchedule),ProfileSchedule.Colunas.Tabela);
	}
	
	public long Update(Profile profile)
	{
		return r.Update(Profile.Colunas.Tabela,
							RepositoryProfileScript.AtualizarTbPerfil(profile),
							Profile.Colunas.Id + "=?",
							new String[]{String.valueOf(profile.Id)});
	}
	
	public long Update(ProfileSchedule profileSchedule)
	{
		return r.Update(ProfileSchedule.Colunas.Tabela,
							RepositoryProfileScheduleScript.Update(profileSchedule),
							ProfileSchedule.Colunas.Id + "=?",
							new String[]{String.valueOf(profileSchedule.Id)});
	}
	
	public long UpdateProfileSetActiveByDifferentId(int id,boolean active)
	{
		return r.Update(Profile.Colunas.Tabela,
							RepositoryProfileScript.UpdateProfileSetActive(active),
							Profile.Colunas.Id + " <> " + id,
						null);
	}
	
	public long UpdateProfileSetActiveById(int id,boolean active)
	{
		return r.Update(Profile.Colunas.Tabela,
							RepositoryProfileScript.UpdateProfileSetActive(active),
							Profile.Colunas.Id + "=?",
							new String[]{String.valueOf(id)});
	}
	
	public long UpdateProfileSetDefaultByDifferentId(int id,boolean pDefault)
	{
		return r.Update(Profile.Colunas.Tabela,
							RepositoryProfileScript.UpdateProfileSetDefault(pDefault),
							Profile.Colunas.Id + " <> " + id,
						null);
	}
	
	public long UpdateProfileSetDefaultById(int id,boolean pDefault)
	{
		return r.Update(Profile.Colunas.Tabela,
							RepositoryProfileScript.UpdateProfileSetDefault(pDefault),
							Profile.Colunas.Id + "=?",
							new String[]{String.valueOf(id)});
	}
	
	public long ApagarPerfil(int id)
	{
		return r.Delete(Profile.Colunas.Tabela,Profile.Colunas.Id + "=?",new String[]{String.valueOf(id)});
	}
	
	public List<Profile> ListarPerfis() throws Exception
	{
		try
		{
			return r.LoadProfile();
		}
		catch (Exception e) {
			// TODO: handle exception
			throw new Exception(e.getMessage());
		}
	}
	
	public Profile CarregaPerfilPorId(int id) throws Exception
	{
		try
		{
		return r.LoadProfile(id);
		}
		catch (Exception e) {
			// TODO: handle exception
			throw new Exception(e.getMessage());
		}
	}

	public ProfileSchedule FindProfileScheduleByProfile(int idProfile) throws Exception
	{
		try
		{
			Cursor c = r.FindByOneCollumn(ProfileSchedule.Colunas.Tabela, ProfileSchedule.Colunas.IdPerfil,String.valueOf(idProfile));
			
			ProfileSchedule profileSchedule = new ProfileSchedule();
			if (c.moveToFirst()) {
				
				int idId = c.getColumnIndex(ProfileSchedule.Colunas.Id);
				int idPerfil = c.getColumnIndex(ProfileSchedule.Colunas.IdPerfil);
				int idDateOfBegin = c.getColumnIndex(ProfileSchedule.Colunas.DateOfBegin);
				int idDateOfEnd = c.getColumnIndex(ProfileSchedule.Colunas.DateOfEnd);
				int idFriday = c.getColumnIndex(ProfileSchedule.Colunas.Friday);
				int idMonday = c.getColumnIndex(ProfileSchedule.Colunas.Monday);
				int idSaturday = c.getColumnIndex(ProfileSchedule.Colunas.Saturday);
				int idSunday = c.getColumnIndex(ProfileSchedule.Colunas.Sunday);
				int idThursday = c.getColumnIndex(ProfileSchedule.Colunas.Thursday);
				int idTuesday = c.getColumnIndex(ProfileSchedule.Colunas.Tuesday);
				int idWednesday = c.getColumnIndex(ProfileSchedule.Colunas.Wednesday);
				int idActive = c.getColumnIndex(ProfileSchedule.Colunas.Active);

				
				do {
										
					profileSchedule.Id = c.getInt(idId);
					profileSchedule.IdPerfil = c.getInt(idPerfil);
					profileSchedule.DateOfBegin = c.getString(idDateOfBegin);
					profileSchedule.DateOfEnd = c.getString(idDateOfEnd);
					profileSchedule.Monday = c.getInt(idMonday) == 1;
					profileSchedule.Thursday = c.getInt(idThursday) == 1;
					profileSchedule.Tuesday = c.getInt(idTuesday) == 1;
					profileSchedule.Wednesday = c.getInt(idWednesday) == 1;
					profileSchedule.Friday = c.getInt(idFriday) == 1;
					profileSchedule.Saturday = c.getInt(idSaturday) == 1;
					profileSchedule.Sunday = c.getInt(idSunday) == 1;
					profileSchedule.Active = c.getInt(idActive) == 1;
					
				} while (c.moveToNext());
			}
			
			return profileSchedule;
	
		}
		catch (Exception e) {
			// TODO: handle exception
			throw new Exception(e.getMessage());
		}
	}

	public void SetAlarm(Context ctx)
	{
		Intent it = new Intent("EA");
		PendingIntent p = PendingIntent.getBroadcast(ctx, 0, it, 0);
		
		
		AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
		Calendar c = Calendar.getInstance();
		c.add(Calendar.SECOND, 5);
		
		//86400 * 1000
		am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 60 * 1000, p);
	}
	
	public void SetVolume(Context ctx,String idPerfil) throws Exception
	{
		Profile p = CarregaPerfilPorId(Integer.parseInt(idPerfil));
		UpdateProfileSetActiveByDifferentId(p.Id, false);
		UpdateProfileSetActiveById(p.Id, true);
		
		AudioManager audioManager = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
		
		if((audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT ||
				audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) && 
				p.Ringtong > 0)
		{
			audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		}
		
		if(p.Vibrate)
			audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
		
		if(p.Silent)
			audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		
		if(!p.Silent || !p.Vibrate)
		{
			audioManager.setStreamVolume(
					AudioManager.STREAM_RING, 
					p.Ringtong,
					AudioManager.FLAG_VIBRATE);
			
			audioManager.setStreamVolume(
					AudioManager.STREAM_MUSIC, 
					p.Multimedia,
					AudioManager.FLAG_VIBRATE);
			
			audioManager.setStreamVolume(
					AudioManager.STREAM_ALARM, 
					p.Alarme,
					AudioManager.FLAG_VIBRATE);
			
			audioManager.setStreamVolume(
					AudioManager.STREAM_NOTIFICATION, 
					p.Notification,
					AudioManager.FLAG_VIBRATE);
            
			Toast.makeText(ctx,"Perfil Aplicado!",Toast.LENGTH_LONG).show();
			Mensagem(ctx,p.Name);
		}
	}
	
	public void Mensagem(Context ctx,String perfil)
    {
    	NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    	int icon = br.gerenciadorAudio.R.drawable.music_icon_64;
    	CharSequence tickerText = "Perfil Atual: " + perfil;
    	long when = System.currentTimeMillis();

    	Notification notification = new Notification(icon, tickerText, when);
    	notification.flags = Notification.FLAG_ONGOING_EVENT;
    	
    	Context context = ctx.getApplicationContext();
    	CharSequence contentTitle = "Perfil Atual";
    	CharSequence contentText = perfil;
    	Intent notificationIntent = new Intent(ctx, ListProfileActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
      	mNotificationManager.notify(1, notification);
    }
	
	public List<ProfileSchedule> FindScheduleActiveByBeginHour(String dataHora)
	{
		Cursor c = null;
		try 
		{
			c = r.FindByOneCollumn(ProfileSchedule.Colunas.Tabela, ProfileSchedule.Colunas.DateOfBegin,dataHora);
			
			List<ProfileSchedule> profileSchedules = new ArrayList<ProfileSchedule>();
			
			if (c.moveToFirst()) 
			{
				
				int idId = c.getColumnIndex(ProfileSchedule.Colunas.Id);
				int idPerfil = c.getColumnIndex(ProfileSchedule.Colunas.IdPerfil);
				int idDateOfBegin = c.getColumnIndex(ProfileSchedule.Colunas.DateOfBegin);
				int idDateOfEnd = c.getColumnIndex(ProfileSchedule.Colunas.DateOfEnd);
				int idFriday = c.getColumnIndex(ProfileSchedule.Colunas.Friday);
				int idMonday = c.getColumnIndex(ProfileSchedule.Colunas.Monday);
				int idSaturday = c.getColumnIndex(ProfileSchedule.Colunas.Saturday);
				int idSunday = c.getColumnIndex(ProfileSchedule.Colunas.Sunday);
				int idThursday = c.getColumnIndex(ProfileSchedule.Colunas.Thursday);
				int idTuesday = c.getColumnIndex(ProfileSchedule.Colunas.Tuesday);
				int idWednesday = c.getColumnIndex(ProfileSchedule.Colunas.Wednesday);
				int idActive = c.getColumnIndex(ProfileSchedule.Colunas.Active);

				
				do {
					ProfileSchedule profileSchedule = new ProfileSchedule();
					
					profileSchedule.Id = c.getInt(idId);
					profileSchedule.IdPerfil = c.getInt(idPerfil);
					profileSchedule.DateOfBegin = c.getString(idDateOfBegin);
					profileSchedule.DateOfEnd = c.getString(idDateOfEnd);
					profileSchedule.Monday = c.getInt(idMonday) == 1;
					profileSchedule.Thursday = c.getInt(idThursday) == 1;
					profileSchedule.Tuesday = c.getInt(idTuesday) == 1;
					profileSchedule.Wednesday = c.getInt(idWednesday) == 1;
					profileSchedule.Friday = c.getInt(idFriday) == 1;
					profileSchedule.Saturday = c.getInt(idSaturday) == 1;
					profileSchedule.Sunday = c.getInt(idSunday) == 1;
					profileSchedule.Active = c.getInt(idActive) == 1;
					
					profileSchedules.add(profileSchedule);
					
				} while (c.moveToNext());
			
			}
			
			return profileSchedules;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(Constant.categoryLog,"Loc: "  + e.getLocalizedMessage() + " Msg:" + e.getMessage());
		}
		finally
		{
			c.close();
		}
		
		return null;
	}
	
	public List<ProfileSchedule> FindScheduleActiveByEndHour(String dataHora)
	{
		Cursor c = null;
		try 
		{
			c = r.FindByOneCollumn(ProfileSchedule.Colunas.Tabela, ProfileSchedule.Colunas.DateOfEnd,dataHora);
			
			List<ProfileSchedule> profileSchedules = new ArrayList<ProfileSchedule>();
			
			if (c.moveToFirst()) 
			{
				
				int idId = c.getColumnIndex(ProfileSchedule.Colunas.Id);
				int idPerfil = c.getColumnIndex(ProfileSchedule.Colunas.IdPerfil);
				int idDateOfBegin = c.getColumnIndex(ProfileSchedule.Colunas.DateOfBegin);
				int idDateOfEnd = c.getColumnIndex(ProfileSchedule.Colunas.DateOfEnd);
				int idFriday = c.getColumnIndex(ProfileSchedule.Colunas.Friday);
				int idMonday = c.getColumnIndex(ProfileSchedule.Colunas.Monday);
				int idSaturday = c.getColumnIndex(ProfileSchedule.Colunas.Saturday);
				int idSunday = c.getColumnIndex(ProfileSchedule.Colunas.Sunday);
				int idThursday = c.getColumnIndex(ProfileSchedule.Colunas.Thursday);
				int idTuesday = c.getColumnIndex(ProfileSchedule.Colunas.Tuesday);
				int idWednesday = c.getColumnIndex(ProfileSchedule.Colunas.Wednesday);
				int idActive = c.getColumnIndex(ProfileSchedule.Colunas.Active);

				
				do {
					ProfileSchedule profileSchedule = new ProfileSchedule();
					
					profileSchedule.Id = c.getInt(idId);
					profileSchedule.IdPerfil = c.getInt(idPerfil);
					profileSchedule.DateOfBegin = c.getString(idDateOfBegin);
					profileSchedule.DateOfEnd = c.getString(idDateOfEnd);
					profileSchedule.Monday = c.getInt(idMonday) == 1;
					profileSchedule.Thursday = c.getInt(idThursday) == 1;
					profileSchedule.Tuesday = c.getInt(idTuesday) == 1;
					profileSchedule.Wednesday = c.getInt(idWednesday) == 1;
					profileSchedule.Friday = c.getInt(idFriday) == 1;
					profileSchedule.Saturday = c.getInt(idSaturday) == 1;
					profileSchedule.Sunday = c.getInt(idSunday) == 1;
					profileSchedule.Active = c.getInt(idActive) == 1;
					
					profileSchedules.add(profileSchedule);
					
				} while (c.moveToNext());
			
			}
			
			return profileSchedules;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			c.close();
		}
		
		return null;
	}
}
